<?php
/**
 * Created by PhpStorm.
 * User: mayn
 * Date: 2018/2/4
 * Time: 16:58
 */

namespace Nuoche\Controller;

use Common\Controller\NuochebaseController;
use Nuoche\Logic\AxnLogic;
use Think\Exception;

class CompanyController extends NuochebaseController{

    public function index(){
        $nid = I('nid','0','int');// thinkphp 3.2.3 使用方式
        $ncode=I('ncode','','trim');
        if($nid > 0){
            $info = M('nuoche_chezhu')->find($nid);
            if($info){
                if($ncode != $info['ncode']){
                    $this->error("扫描的二维码不存在!");
                }
                $tel = strlen($info['tel']);
                $plateNum = strlen($info['platenum']);

                //用户每次扫码进行一次记录 用于统计改产品每天被多少人访问，
                $ipaddr = get_client_ip();
                $provin = $city = '';
                if($ipaddr) {
                    $area   = sinaIP($ipaddr);
                    $provin = $area['province'];
                    $city   = $area['city'];
                }

                M('nuoche_call')->add(array(
                    'nid'     => $nid,
                    'callednum'    => $info['tel'],
                    'calltype'       => 3,//该类型为扫码访问的此类型
                    'ip'         => $ipaddr,
                    'province'   => $provin,
                    'city'       => $city,
                    'createtime' => date('Y-m-d H:i:s'),
                ));

                if($tel > 0 && $plateNum > 0 ){
                    //先获取是否存在 过期时间
                    //如果在过期时间之内则 使用原来分机码
                    //$expirationTime = $info['expirationtime'];

                    //如果再过期时间之外则 解除原来分机码，分分配新的分机码

                    //取消上次绑定信息
                    $subsId = $info['subsid'];
                    $secretNo = $info['secretno'];
                    session('th_count'.$nid,1);

                        if($subsId && $secretNo){
                            $axn = new AxnLogic();
                            $axn->unbindSubscription($subsId,$secretNo);
                        }
                    $extension = sp_random_num(3);
                    $this->assign("nid",$nid);
                    $this->assign('ncode',$ncode);
                    $this->assign('plateNum',$info['platenum']);
                    $this->assign('extension',$extension);
                    $this->display('nuoche');

                }else{
                    $this->assign("nid",$nid);
                    $this->assign('ncode',$ncode);
                    $this->display();
                }
            }else{
                $this->error("扫描的二维码不存在!");
            }
        }else{
            $this->error('扫描的二维码不存在！');
        }
    }
    public function bindtonghua(){
        $nid = I('nid','','trim');
        $ncode=I('ncode','','trim');
        $plateNum = I('plateNum','','trim');
        $plateNum = strtoupper($plateNum);
        $extension = I('extension','','trim');
        $nowtime = time();

        $thCount = session('th_count'.$nid);
        $str_lastsendtime = "th_lastsendtime".$nid;
        $lastsendtime = session($str_lastsendtime);
        \Think\Log::write('$thCount::::::'.$thCount);
        if($thCount == 1){
            session($str_lastsendtime, $nowtime);
            session('th_count'.$nid,$thCount+1);
            if($nid>0){
                $info = M('nuoche_chezhu')->where(array('nid'=>$nid,'ncode'=>$ncode,'platenum'=>$plateNum))->find();
                if($info){
                    $axn = new AxnLogic();
                    $expirationTime = date('Y-m-d H:i:s',time()+1200);
                    $mobile = $info['tel'];
                    $res = $axn->bindAxnExtension($mobile,$extension,$expirationTime);
                    if($res->Message == 'OK'){
                        $secretBindDTO =  $res->SecretBindDTO;
                        $extension = $secretBindDTO->Extension;
                        $secretNo = $secretBindDTO -> SecretNo;
                        $subsId  = $secretBindDTO -> SubsId;
                        $data = array(
                            'subsId' => $subsId,
                            'secretNo' => $secretNo,
                            'expirationTime' => $expirationTime,
                            'extension' => $extension,
                            'lastNoticeTime' => date('Y-m-d H:i:s'),
                            'thCount'=>$info['thcount']+1
                        );
                        if(M('nuoche_chezhu')->where(array('nid'=>$nid,'ncode'=>$ncode,'platenum'=>$plateNum))->save($data)){

                            $ipaddr = get_client_ip();
                            $provin = $city = '';
                            if($ipaddr) {
                                $area   = sinaIP($ipaddr);
                                $provin = $area['province'];
                                $city   = $area['city'];
                            }

                            M('nuoche_call')->add(array(
                                'nid'     => $nid,
                                'callednum'    => $mobile,
                                'calltype'       => 2,
                                'ip'         => $ipaddr,
                                'province'   => $provin,
                                'city'       => $city,
                                'createtime' => date('Y-m-d H:i:s'),
                            ));

                            $msg = "true";
                            $result['msg'] = $msg;
                            $result['secretNo'] = $secretNo;
                            session('secretNo'.$nid,$secretNo);
                            $this->ajaxReturn($result);
                            return;
                        }
                    }else{
                        $msg = "分配分机码失败";
                    }
                }else{
                    $msg = "号码不存在";
                }
            }else{
                $msg = "二维码不存在";
            }
        }else if($thCount >3){
            if($lastsendtime && $nowtime - $lastsendtime < 160) {
                $msg = "您打点话的次数过于频繁，请稍后尝试(需要间隔3分钟以上)";
                $result['msg'] = $msg;
                $this->ajaxReturn($result);
                return;
            }else{
                session('th_count'.$nid,2);
                session($str_lastsendtime, $nowtime);
                $msg = "true";
                $result['msg'] = $msg;
                $result['secretNo'] = session('secretNo'.$nid);
                $this->ajaxReturn($result);
                return;
            }
        }else{
            session('th_count'.$nid,$thCount+1);
            $msg = "true";
            $result['msg'] = $msg;
            $result['secretNo'] = session('secretNo'.$nid);
            $this->ajaxReturn($result);
            return;
        }

        $result['msg'] = $msg;
        $this->ajaxReturn($result);
    }

    public function introd(){
        $this->display();
    }

    public function unbind(){
        $this->display();
    }

    public function dounbind(){
       // $nid = I('nid','','trim');
        //$ncode=I('ncode','','trim');
        $mobile = I('telNum','','trim');
        $plateNum = I('plateNum','','trim');
        $plateNum = strtoupper($plateNum);

        $vCode = I('vCode','','trim');
        if(empty($mobile) || !preg_match('/^1[3|4|5|7|8]\d{9}$/', $mobile)) {
            $msg = "手机号格式错误";
            $this->error($msg);
            return;
        }else {
            $info = D("nuoche_chezhu")->where(array('plateNum' => $plateNum, 'tel' => $mobile))->find();
        }

        if(!$info) {
             $msg='车牌号与对应的手机号码不正确，不能进行解绑！请核实在系统中注册时的车牌号与电话号码是否正确！';
        } else if(empty($vCode)
            || !preg_match('/^\d{4}$/', $vCode)
            || (!sp_check_mobile_verify_code(4, $mobile, $vCode))) {
            $msg="语音验证码错误";
        }else{
            $data = array(
                'tel' => null,
                'plateNum' => null,
                'regTime' => null,
                'noticeCount' => null,
                'lastNoticeTime' => null
            );
            if(D("nuoche_chezhu")->where(array('nid' => $info['nid'] , 'ncode'=>$info['ncode']))->save($data)){
                $msg = "解绑成功！";
                $this->success($msg,UU('Nuoche/company/index',array('nid'=>$info['nid'],'ncode'=>$info['ncode'])));
                return;
            }else{
                $msg = "解绑失败！";
            }
        }
        $this->error($msg);
    }

    public function nuoche(){
        $nid = I('nid','','trim');
        $ncode=I('ncode','','trim');
        $mobile = I('telNum','','trim');
        $plateNum = I('plateNum','','trim');
        $vCode = I('vCode','','trim');
        $plateNum = strtoupper($plateNum);
        if(empty($mobile) || !preg_match('/^1[3|4|5|7|8]\d{9}$/', $mobile)) {
            $msg = "手机号格式错误";
        } else if(D("nuoche_chezhu")->where(array('plateNum' => $plateNum))->count() > 0) {
            $msg='该车牌号已经注册！';
        } else if(D("nuoche_chezhu")->where(array('tel' => $mobile))->count() > 3){
            $msg='该手机号已经超过可注册的最大上线';
        }else if (D("nuoche_chezhu")->where(array('nid' => $nid , 'ncode'=>$ncode))->count()!=1){
            $msg='该二维码不存在！';
        } else if(empty($vCode)
            || !preg_match('/^\d{4}$/', $vCode)
            || (!sp_check_mobile_verify_code(4, $mobile, $vCode))) {
            $msg="语音验证码错误";
        }else{
            $data = array(
                'tel' => $mobile,
                'plateNum' => $plateNum,
                'regTime' => date('Y-m-d H:i:s')
            );
            if(D("nuoche_chezhu")->where(array('nid' => $nid , 'ncode'=>$ncode))->save($data)){

                //当注册完成车辆信息时需要检测改手机号是否 已经注册到系统中，如果未注册到系统中则进行注册，

                $this->reguse($mobile);

                $extension = sp_random_num(3);
                session('th_count'.$nid,1);
                $this->assign('extension',$extension);
                $this->assign("nid",$nid);
                $this->assign("ncode",$ncode);
                $this->assign("plateNum",$plateNum);
                $this->display();
                return;
            }else{
                $msg = "注册失败";
            }
        }
        $this->error($msg);
    }

    function yuyints(){
        $nid = I('nid','0','int');
        $ncode = I('ncode','','trim');
        $plateNum = I('plateNum','','trim');
        $plateNum = strtoupper($plateNum);
        $nowtime = time();
        $str_lastsendtime = "yuyin_lastsendtime".$nid;
        $lastsendtime = session($str_lastsendtime);
        session($str_lastsendtime, $nowtime);
        if($lastsendtime && $nowtime - $lastsendtime < 160) {
            $msg = "我们已经帮您联系车主，请耐心等待！发送时间间隔太短,(需要间隔3分钟以上)";
            $result['msg'] = $msg;
            $this->ajaxReturn($result);
            return;
        }
        if($nid>0){
            $info = M('nuoche_chezhu')->where(array('nid'=>$nid,'ncode'=>$ncode,'platenum'=>$plateNum))->find();
            if($info){
                $tel = $info['tel'];
                $ttsCode="TTS_125020071";//TTS_124930076 --> 验证码  ：：：TTS_125020071  -->  挪车提示
                $ttsParam=array("plateNum" => $plateNum);//array("product" => "大友印相挪车","code" => $code); --> 短信验证码
                $content = singleCallByTts($tel,$nid,$ttsCode,$ttsParam);
                $noticeCount = $info['noticecount'];
                M('nuoche_chezhu')->where(array('nid'=>$nid,'ncode'=>$ncode,'platenum'=>$plateNum))->save(array('lastNoticeTime'=>date('Y-m-d H:i:s'),'noticeCount'=>$noticeCount+1));

                $ipaddr = get_client_ip();
                $provin = $city = '';
                if($ipaddr) {
                    $area   = sinaIP($ipaddr);
                    $provin = $area['province'];
                    $city   = $area['city'];
                }

                M('nuoche_call')->add(array(
                    'nid'     => $nid,
                    'callednum'    => $tel,
                    'calltype'       => 1,
                    'ip'         => $ipaddr,
                    'province'   => $provin,
                    'city'       => $city,
                    'createtime' => date('Y-m-d H:i:s'),
                ));


                if($content->Code == 'OK'){
                    $msg = "我们已经帮您联系车主，请耐心等待！";
                    $result['msg'] = $msg;
                    $this->ajaxReturn($result);
                    return;
                }else{
                    $msg = "发送语音提示失败";
                }
            }else{
                $msg = "号码不存在";
            }
        }else{
            $msg = "二维码不存在";
        }
        $result['msg'] = $msg;
        $this->ajaxReturn($result);
    }

}